package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import modelos.Usuario;

public class DAOUsuario 
{
	private Connection connection;
	private PreparedStatement comando;
	private ResultSet result;
	
	public DAOUsuario()
	{
		connection = ConnectionFactory.createConnection();
	}
	
	public List<Usuario> buscaUsuarios() throws Exception
	{
		List<Usuario> usuarios = new ArrayList<Usuario>();
		Usuario user = null;
		
		comando = connection.prepareStatement("SELECT * FROM usuarios");
		
		result = comando.executeQuery();
		
		while(result.next())
		{
			user = new Usuario();
			
			user.setId(result.getInt("id"));
			user.setNome(result.getString("nome"));
			user.setEmail(result.getString("email"));
			user.setSenha(result.getString("senha"));
			
			usuarios.add(user);
		}
//		this.fechaConexao();
		
		return usuarios;
	}
	
	public void insereUsuario(String nome, String email, String senha) throws SQLException
	{
		comando = connection.prepareStatement("INSERT INTO usuarios (nome, email, senha) VALUES (?,?,?)");
		
		comando.setString(1, nome);
		comando.setString(2, email);
		comando.setString(3, senha);
		
		comando.execute();
		
		this.fechaConexao();
	}
	
	public void alteraUsuario(int id, String nome, String email, String senha) throws SQLException
	{
		comando = connection.prepareStatement("UPDATE usuarios SET nome = ?, email = ?, senha = ? WHERE id = ?");
		
		comando.setString(1, nome);
		comando.setString(2, email);
		comando.setString(3, senha);
		comando.setInt(4, id);
		
		comando.execute();
		
		this.fechaConexao();
		
	}
	
	public void excluiUsuario(int id) throws SQLException
	{
		comando = connection.prepareStatement("DELETE FROM usuarios WHERE id = ?");
		
		comando.setInt(1, id);
		
		comando.execute();
		
		this.fechaConexao();
	}
	
	public void fechaConexao() throws SQLException
	{
		connection.close();
	}
	
}
